package com.ruoyi.web.controller.system;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.cs.domain.TUser;
import com.ruoyi.system.mapper.SysLogininforMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@SuppressWarnings("ALL")
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLogininforMapper sysLogininforMapper;

    @Autowired
    private RedisCache redisCache;


//    /**
//     * 获取用户列表
//     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(SysUser user)
//    {
//        startPage();
//        List<SysUser> list = userService.selectUserList(user);
//        return getDataTable(list);
//    }
//
//    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
//    @GetMapping("/export")
//    public AjaxResult export(SysUser user)
//    {
//        List<SysUser> list = userService.selectUserList(user);
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.exportExcel(list, "用户数据");
//    }
//
//    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:import')")
//    @PostMapping("/importData")
//    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        String operName = loginUser.getUsername();
//        String message = userService.importUser(userList, updateSupport, operName);
//        return AjaxResult.success(message);
//    }
//
//    @GetMapping("/importTemplate")
//    public AjaxResult importTemplate()
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//        return util.importTemplateExcel("用户数据");
//    }

//    /**
//     * 根据用户编号获取详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
//    @GetMapping(value = { "/", "/{userId}" })
//    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
//    {
//        AjaxResult ajax = AjaxResult.success();
//        List<SysRole> roles = roleService.selectRoleAll();
//        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
//        ajax.put("posts", postService.selectPostAll());
//        if (StringUtils.isNotNull(userId))
//        {
//            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
//            ajax.put("postIds", postService.selectPostListByUserId(userId));
//            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
//        }
//        return ajax;
//    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @RequestMapping(name="新增用户",value="add",method = RequestMethod.POST)
    public AjaxResult add(@RequestBody SysUser user)
    {

        if (StringUtils.isEmpty(user.getUserPhone())) {
            return new AjaxResult(Constants.FAILCODE,"手机号不能为空！");
        }
        if (!Arrays.asList(Constants.USERPHONELIST).contains(user.getUserPhone())){
            return new AjaxResult(Constants.FAILCODE,"该手机号无操作权限！");
        }
        //短信验证码前缀
        String key = Constants.PHONE_CODE+user.getUserPhone();
        //从Redis获取短信验证码
        String code1 = redisCache.getCacheObject(key);
        if (StringUtils.isEmpty(code1) || !code1.equals(user.getCodePhone())) {
            return new AjaxResult(Constants.FAILCODE,"验证码错误!");
        }
        redisCache.deleteObject(key);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return new AjaxResult(Constants.FAILCODE,"用户已过期，请重新登录!");
        }else {
            String userName = loginUser.getUsername();
            if (!"admin".equals(userName)) {
                return new AjaxResult(Constants.FAILCODE,"管理员才有权限!");
            }
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return new AjaxResult(Constants.FAILCODE,"新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return new AjaxResult(Constants.FAILCODE,"新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
//        else if (StringUtils.isNotEmpty(user.getEmail())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
//        {
//            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setDeptId(100L);
        user.setRoleIds(new Long[]{2L});
        user.setPostIds(new Long[0]);
        user.setStatus("0");
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setDelFlag(Constants.SUCCESS);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequestMapping(name="修改用户",value="edit",method = RequestMethod.POST)
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {

        if (StringUtils.isEmpty(user.getUserPhone())) {
            return new AjaxResult(Constants.FAILCODE,"手机号不能为空！");
        }
        if (!Arrays.asList(Constants.USERPHONELIST).contains(user.getUserPhone())){
            return new AjaxResult(Constants.FAILCODE,"该手机号无操作权限！");
        }
        //短信验证码前缀
        String key = Constants.PHONE_CODE+user.getUserPhone();
        //从Redis获取短信验证码
        String code1 = redisCache.getCacheObject(key);
        if (StringUtils.isEmpty(code1) || !code1.equals(user.getCodePhone())) {
            return new AjaxResult(Constants.FAILCODE,"验证码错误!");
        }
        redisCache.deleteObject(key);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return new AjaxResult(Constants.FAILCODE,"用户已过期，请重新登录!");
        }else {
            String userName = loginUser.getUsername();
            if (!"admin".equals(userName)) {
                return new AjaxResult(Constants.FAILCODE,"管理员才有权限!");
            }
        }
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return new AjaxResult(Constants.FAILCODE,"修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return new AjaxResult(Constants.FAILCODE,"修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 冻结用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:stop')")
    @Log(title = "用户管理", businessType = BusinessType.STOP)
    @RequestMapping(name="冻结用户",value="stop",method = RequestMethod.GET)
    public AjaxResult stop(String userName)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return new AjaxResult(Constants.FAILCODE,"用户已过期，请重新登录!");
        }else {
            String userName1 = loginUser.getUsername();
            if (!"admin".equals(userName1)) {
                return new AjaxResult(Constants.FAILCODE,"管理员才有权限!");
            }
        }
        SysUser user = userService.selectUserByUserName1(userName);
        userService.checkUserAllowed(user);
        return toAjax(userService.updateDelflag(Constants.FAIL,userName));
    }

    /**
     * 解冻用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:enable')")
    @Log(title = "用户管理", businessType = BusinessType.ENABLE)
    @RequestMapping(name="解冻用户",value="enable",method = RequestMethod.GET)
    public AjaxResult enable(String userName)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return new AjaxResult(Constants.FAILCODE,"用户已过期，请重新登录!");
        }else {
            String userName1 = loginUser.getUsername();
            if (!"admin".equals(userName1)) {
                return new AjaxResult(Constants.FAILCODE,"管理员才有权限!");
            }
        }
        SysUser user = userService.selectUserByUserName1(userName);
        userService.checkUserAllowed(user);
        return toAjax(userService.updateDelflag(Constants.SUCCESS,userName));
    }
    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @RequestMapping(name="删除用户",value="remove",method = RequestMethod.GET)
    public AjaxResult remove(String userIds,String codePhone,String userPhone)
    {
        if (StringUtils.isEmpty(userPhone)) {
            return new AjaxResult(Constants.FAILCODE,"手机号不能为空！");
        }
        if (!Arrays.asList(Constants.USERPHONELIST).contains(userPhone)){
            return new AjaxResult(Constants.FAILCODE,"该手机号无操作权限！");
        }
        //短信验证码前缀
        String key = Constants.PHONE_CODE+userPhone;
        //从Redis获取短信验证码
        String code1 = redisCache.getCacheObject(key);
        if (StringUtils.isEmpty(code1) || !code1.equals(codePhone)) {
            return new AjaxResult(Constants.FAILCODE,"验证码错误!");
        }
        redisCache.deleteObject(key);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return new AjaxResult(Constants.FAILCODE,"用户已过期，请重新登录!");
        }else {
            String userName1 = loginUser.getUsername();
            if (!"admin".equals(userName1)) {
                return new AjaxResult(Constants.FAILCODE,"管理员才有权限!");
            }
        }
        return toAjax(userService.deleteUserByIds(Convert.toLongArray(userIds)));
    }
//
//    /**
//     * 重置密码
//     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/resetPwd")
//    public AjaxResult resetPwd(@RequestBody SysUser user)
//    {
//        userService.checkUserAllowed(user);
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setUpdateBy(SecurityUtils.getUsername());
//        return toAjax(userService.resetPwd(user));
//    }
//
//    /**
//     * 状态修改
//     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/changeStatus")
//    public AjaxResult changeStatus(@RequestBody SysUser user)
//    {
//        userService.checkUserAllowed(user);
//        user.setUpdateBy(SecurityUtils.getUsername());
//        return toAjax(userService.updateUserStatus(user));
//    }


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:userList')")
    @RequestMapping(name="获取用户列表",value="userList",method = RequestMethod.POST)
    public TableDataInfo userList(@RequestBody  SysUser user)
    {
        startPage(user.getPageNum(),user.getPageSize());
        List<SysUser> list = userService.selectUserList1(user);
        if (list != null && list.size()>0) {
            for (SysUser sysUser : list) {
                String time = sysLogininforMapper.getLastLonginTime(sysUser.getUserName());
                if (StringUtils.isNotEmpty(time)){
                    sysUser.setLoginDate(DateUtils.parseDate(time));
                }
                sysUser.setDept(null);
            }
        }
        return getDataTable(list);
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation("获取用户信息详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:getInfo')")
    @RequestMapping(name="获取用户信息详细信息",value="getInfo",method = RequestMethod.GET)
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null){
            SysUser user = loginUser.getUser();
            if (user != null) {
                String userName = user.getUserName();
                SysUser ss = userService.selectUserByUserName1(userName);
                ss.setDept(null);
                return  AjaxResult.success(ss);
            }
            return new AjaxResult(Constants.FAILCODE,"请重新登录！");
        }else {
            return new AjaxResult(Constants.FAILCODE,"请重新登录！");
        }
    }


}
